package com.android.kmlmrg.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestGetUserEvent;
import com.android.kmlmrg.event.UserFieldChangedEvent;
import com.android.kmlmrg.listener.custom.RestGetUserListener;
import com.android.kmlmrg.listener.custom.UserFieldListener;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.rest.method.GetUser;
import com.android.kmlmrg.utils.Const;
import com.android.kmlmrg.views.ViewContact;

public class ContactAdapter extends BaseAdapter implements Const, UserFieldListener{


	/**LOG**/
	private static final  String LOG_TAG = ContactAdapter.class.getName();
	private Activity activity;
	private List<User> data ;
	private static LayoutInflater inflater=null;

	
	public ContactAdapter (Activity a, List<User> l){
		User.addListener(this);
		activity = a;
		data = new ArrayList<User>(l);
		inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}
	public int getCount() {
		return data.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int itemId) {
		return itemId;
	}

	public View getView(int position, View view, ViewGroup parent) {
		Log.i(LOG_TAG, "START - getView");
		View myContactRow = view;
		if(myContactRow==null)
			myContactRow = inflater.inflate(R.layout.list_row, null);
		TextView nom = (TextView)myContactRow.findViewById(R.id.list_nom);
		TextView prenom = (TextView)myContactRow.findViewById(R.id.list_prenom);
		ImageView image = (ImageView)myContactRow.findViewById(R.id.list_image);
		User user = data.get(position);
		nom.setText(user.getNom());
		prenom.setText(user.getPrenom());
		if(user.getPathExternalStorage() != null ){
			try{
			 Bitmap bitmap =  BitmapFactory.decodeFile(user.getPathExternalStorage());
			image.setImageBitmap(bitmap);
			}catch(OutOfMemoryError e){
				image.setImageResource(R.drawable.contact);
			}
		}else{
			image.setImageResource(R.drawable.contact);
		}
		Log.i(LOG_TAG, "END - getView");
	
		return myContactRow;
	}
	
	public List<User> getData(){
		return data;
	}
	public void userFielChanged(UserFieldChangedEvent event) {
		Log.i(LOG_TAG, "START - userFielChanged");
		this.notifyDataSetChanged();
		Log.i(LOG_TAG, "END - userFielChanged");
	}

}
